/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.creator.logical.links.сore;

import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;
import ru.creator.logical.links.сore.util.Log;

/**
 *
 * @author ~jo-MA-jo~
 */
public class MessageViewer implements Runnable{
    private Thread th;
    private ConcurrentLinkedQueue <String[]> mq;
    private HashMap<String,MessageСonstructor> mc;
    private List<IRatingWords> rw;
   // private MessageСonstructor mc;
    private Logic logic;
    private Log logger;


    public MessageViewer(Logic logic){
        mq = new ConcurrentLinkedQueue();
        rw = new Vector<IRatingWords>();
        mc = new HashMap<String,MessageСonstructor>();
        this.logic = logic;
        logger = logic.getLogger();
    }

    public void addMessage(String senderID, String Message){
        mq.add(new String[]{senderID, Message});
        if (th==null)start();
        logger.debug("Добавление нового сообщения в MessageViewer (SenderID: "+senderID+" )");
    }

    public void addLinksAnalyzer (IRatingWords obj){
        rw.add(obj);
        logger.debug("Добавление нового анализатора в MessageViewer");
    }


    public synchronized void think(){
        String[] me = mq.poll();
        String senderID = me[0];
        String message = me[1];
        MessageСonstructor m =getСonstructor(senderID);
        logger.debug("Анализ сообщения в MessageViewer");
          for(IRatingWords la:rw){
            m.addHashWords(la.getWords(me));
          }
        logic.getMessageListener().onOutMessage(m.getMessage(message));
    }

    public MessageСonstructor getСonstructor(String senderID) {
        if(mc.containsKey(senderID))
              return mc.get(senderID);
        MessageСonstructor mesConst = new MessageСonstructor(logic, senderID);
        mc.put(senderID, mesConst);
        return mesConst;
    }
    
    public void start(){
        th = new Thread(this);
        th.setPriority(Thread.NORM_PRIORITY);
        th.start();
        logger.debug("Запуск MessageViewer");
    }

    public synchronized void stop() {
        logger.debug("Остановка MessageViewer");
        th = null;
        notify();
    }

    public void run() {
        Thread me = Thread.currentThread();
        while (th == me) {
               if (mq.size()>0)
                   think();
               else
                   stop();
            try {
                th.sleep(500);
            } catch (InterruptedException e) { break; }
        }
        th=null;
    }
}
